package com.study.lession.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.lession.contant.Constants;
import com.study.lession.util.StringUtil;

/**
 * 查看图片
 * 
 * @author warm
 * @version 2019年07月11日
 */
@Controller
public class ShowPicController {

	/**
	 * 查看图片
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/showPic")
	@ResponseBody
	public Object showPic(HttpServletResponse response, String fileName) throws IOException {
		Map<String, Object> map = new HashMap<>();
		if (StringUtil.isEmpty(fileName)) {
			map.put("message", "请输入您需要访问的图片地址！");
			return map;
		}
		
		String fileSavePath = Constants.UPLOAD_FILE_PATH;
		
		File file = new File(fileSavePath + fileName);
		if (!file.exists()) {
			map.put("message", "您访问的资源不存在！");
			return map;
		}
		
		// 图片浏览的表头
		response.setContentType("image/*");
		response.setContentLength((int)file.length());
		
		FileInputStream fis = new FileInputStream(file);
		OutputStream os = response.getOutputStream();
		
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) > 0) {
			os.write(buffer, 0, len);			
		}
		
		fis.close();
		os.close();
		
		return map;
	}
}
